import { defineStore } from 'pinia'
import { favoriteSong, getLikelist } from '@/api/common'

type initStateTy = {
  favoriteSongList: ISongItem[]
  favoriteSongIdList: number[]
}
export const useFavoriteStore = defineStore('favoriteStore', {
  state: (): initStateTy => ({
    favoriteSongList: [],
    favoriteSongIdList: []
  }),
  getters: {},
  actions: {
    initFavoriteSongList() {},
    initFavoriteSongIdList() {
      getLikelist().then(({ ids }) => {
        this.favoriteSongIdList = ids
      })
    },
    hasFavorite(song: ISongItem) {
      return this.favoriteSongIdList.findIndex((id) => id === song?.id) > -1
    },
    favoriteIcon(song: ISongItem | undefined) {
      if (typeof song === 'undefined') {
        return ''
      }
      return this.hasFavorite(song) ? 'icon-favorite' : 'icon-not-favorite'
    },
    favoriteColor(song: ISongItem | undefined, color: string) {
      if (typeof song === 'undefined') {
        return {}
      }
      return {
        color: this.hasFavorite(song) ? color : ''
      }
    },
    toggleFavorite(song: ISongItem | undefined) {
      if (typeof song === 'undefined') {
        return
      }
      let id: number | undefined
      if ((id = song?.id)) {
        favoriteSong(id, !this.hasFavorite(song)).then(async () => {
          // 重新获取喜欢的接口数据
          const { ids } = await getLikelist()
          this.favoriteSongIdList = ids
        })
      }
    }
  }
})
